package org.jim.server.demo.factory;

import lombok.Value;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.jim.server.demo.service.RemoteApi;
import retrofit2.Retrofit;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * https://square.github.io/retrofit/
 *
 * @author: thx
 * @date: 2022/8/7 15:28
 */
public class RemoteApiFactory {

    private static RemoteApi INSTANCE;

    public static RemoteApi getInstance() {
        if (INSTANCE == null) {
            synchronized (RemoteApiFactory.class) {
                if (INSTANCE == null) {
                    Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl("https://mock.apifox.cn/m1/1413524-0-default/")
                            .callbackExecutor(scheduledExecutorService())
                            .addConverterFactory(CustomGsonConverterFactory.create())
                            .build();
                    INSTANCE = retrofit.create(RemoteApi.class);
                }
            }
        }
        return INSTANCE;
    }

    static int corePoolSize = 10;
    /**
     * 线程池维护线程的最大数量
     */
    static int maxPoolSize = 200;

    /**
     * 执行周期性或定时任务
     */
    static ScheduledExecutorService scheduledExecutorService() {
        ScheduledThreadPoolExecutor service = new ScheduledThreadPoolExecutor(corePoolSize, new BasicThreadFactory.Builder().namingPattern("ModSchedule-pool-%d").daemon(true).build()) {
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
            }
        };
        service.setMaximumPoolSize(maxPoolSize);
        return service;
    }
}
